package org.znxs.comfriend.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class ChatHistoryManager {

    // 单例实例
    private static ChatHistoryManager instance;

    // SharedPreferences 的键
    private static final String PREFS_NAME = "ChatHistoryPrefs";
    private static final String CHAT_HISTORY_KEY = "chat_history";

    // Context 对象
    private Context context;

    // 私有构造函数，防止外部实例化
    private ChatHistoryManager(Context context) {
        this.context = context.getApplicationContext();
    }

    // 获取单例实例
    public static synchronized ChatHistoryManager getInstance(Context context) {
        if (instance == null) {
            instance = new ChatHistoryManager(context);
        }
        return instance;
    }

    /**
     * 内部类：表示一条对话消息
     */
    public static class ChatMessage {
        private String senderId; // 发送者 ID
        private String message;  // 消息内容
        private long timestamp; // 时间戳（毫秒）

        public ChatMessage(String senderId, String message, long timestamp) {
            this.senderId = senderId;
            this.message = message;
            this.timestamp = timestamp;
        }

        // Getter 方法
        public String getSenderId() {
            return senderId;
        }

        public String getMessage() {
            return message;
        }

        public long getTimestamp() {
            return timestamp;
        }

        @Override
        public String toString() {
            return "ChatMessage{" +
                    "senderId='" + senderId + '\'' +
                    ", message='" + message + '\'' +
                    ", timestamp=" + timestamp +
                    '}';
        }
    }

    /**
     * 内部类：表示一个对话记录
     */
    public static class ChatRecord {
        private String user1Id; // 用户1的ID
        private String user2Id; // 用户2的ID
        private List<ChatMessage> messages; // 有序的对话消息列表

        public ChatRecord(String user1Id, String user2Id) {
            this.user1Id = user1Id;
            this.user2Id = user2Id;
            this.messages = new ArrayList<>();
        }

        // Getter 和 Setter 方法
        public String getUser1Id() {
            return user1Id;
        }

        public String getUser2Id() {
            return user2Id;
        }

        public List<ChatMessage> getMessages() {
            return messages;
        }

        public void addMessage(ChatMessage message) {
            messages.add(message);
        }

        public void clearMessages() {
            messages.clear();
        }

        @Override
        public String toString() {
            return "ChatRecord{" +
                    "user1Id='" + user1Id + '\'' +
                    ", user2Id='" + user2Id + '\'' +
                    ", messages=" + messages +
                    '}';
        }
    }

    /**
     * 保存对话记录到 SharedPreferences
     */
    public void saveChatRecord(ChatRecord chatRecord) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        // 使用 Gson 将 ChatRecord 转换为 JSON 字符串
        Gson gson = new Gson();
        String json = gson.toJson(chatRecord);

        // 使用用户ID作为键，确保每个对话记录唯一
        String key = generateKey(chatRecord.getUser1Id(), chatRecord.getUser2Id());
        editor.putString(key, json);
        editor.apply();
    }

    /**
     * 从 SharedPreferences 中读取对话记录
     */
    public ChatRecord getChatRecord(String user1Id, String user2Id) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String key = generateKey(user1Id, user2Id);
        String json = sharedPreferences.getString(key, null);

        // 如果存在 JSON 数据，则解析为 ChatRecord
        if (json != null) {
            Gson gson = new Gson();
            return gson.fromJson(json, ChatRecord.class);
        } else {
            // 如果没有数据，返回一个新的空 ChatRecord
            return new ChatRecord(user1Id, user2Id);
        }
    }

    /**
     * 添加一条消息到指定的对话记录中并保存
     */
    public void addMessageToChat(String user1Id, String user2Id, String senderId, String message) {
        ChatRecord chatRecord = getChatRecord(user1Id, user2Id);
        chatRecord.addMessage(new ChatMessage(senderId, message, System.currentTimeMillis()));
        saveChatRecord(chatRecord);
    }

    /**
     * 清空指定对话记录
     */
    public void clearChatRecord(String user1Id, String user2Id) {
        ChatRecord chatRecord = getChatRecord(user1Id, user2Id);
        chatRecord.clearMessages();
        saveChatRecord(chatRecord);
    }

    /**
     * 删除指定对话记录
     */
    public void deleteChatRecord(String user1Id, String user2Id) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String key = generateKey(user1Id, user2Id);
        editor.remove(key);
        editor.apply();
    }

    /**
     * 根据两个用户ID生成唯一的键
     */
    private String generateKey(String user1Id, String user2Id) {
        // 确保键的顺序一致，避免 user1Id 和 user2Id 交换导致不同的键
        if (user1Id.compareTo(user2Id) < 0) {
            return user1Id + "_" + user2Id;
        } else {
            return user2Id + "_" + user1Id;
        }
    }
}